package service

import (
	"fmt"
	"math/rand"
	"rongyy/src/middlewares"
	"rongyy/src/models"
	"strconv"
	"time"
)

type SupplierService struct {
}

func (pc *SupplierService) Create(req *models.SupplierModel) (string, error) {
	rand.Seed(time.Now().UnixNano())
	t := rand.Intn(100)
	ts := strconv.FormatInt(time.Now().UnixMicro(), 10)
	sn := "sa" + ts + strconv.Itoa(t)
	req.Sn = sn
	err := (&models.SupplierModel{}).Create(req)
	if err != nil {
		middlewares.Logger.Println("CaseService Create failed ", err)
		return "", err
	}
	return sn, nil
}

func (pc *SupplierService) Get(id int64) (*models.SupplierModel, error) {
	data, err := (&models.SupplierModel{}).GetById(id)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *SupplierService) Approve(req *models.SupplierModel) error {
	req.Status = "approve"
	err := req.UpdateId()
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return err
	}
	cm, err := req.GetById(req.Id)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return err
	}
	fmt.Println("cm---------", cm.Id, cm)
	// 就医助手---病案通知
	go func() {
		err = (&WxSubscribeMsgService{}).SendSupplierMsg("预约成功", cm.Openid, "pages/receptionApplicationForm/index?active=1", "来院时请携带本人身份证复印件及相关资料")
		if err != nil {
			middlewares.Logger.Println("发送消息错误", err)
		}
	}()
	return nil
}

func (pc *SupplierService) Reject(req *models.SupplierModel) error {
	cm := &models.SupplierModel{}
	c, err := cm.GetById(req.Id)
	if err != nil {
		return err
	}
	if c.Status != "pending" {
		return fmt.Errorf("订单状态错误")
	}
	req.Status = "reject"
	err = req.UpdateId()
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return err
	}
	go func() {
		err = (&WxSubscribeMsgService{}).SendSupplierMsg("驳回申请", c.Openid, "pages/receptionApplicationForm/index?active=1", req.Remark)
		if err != nil {
			middlewares.Logger.Println("发送消息错误", err)
		}
	}()
	return nil
}

func (pc *SupplierService) Query(req *models.ReqSupplier) ([]models.SupplierModel, int64, error) {
	data, total, err := (&models.SupplierModel{}).Query(req)
	if err != nil {
		return nil, 0, err
	}
	return data, total, nil
}
